/*
 * atcmd.c
 *
 *  Created on: 2023年5月26日
 *      Author: zhulijun
 */

#include "my_inc.h"

static void send_at(uint8_t * at_cmd, uint8_t * respond_str);


void send_at_cmds()
{
	/* 退出透传模式 */
	uart2.send_string((uint8_t *)"+++");
	printf("退出透传模式\r\n");
	HAL_Delay(2000);

	/* 以广播模式让手机主动连接蓝牙 */
	send_at((uint8_t*)"AT\r\n",(uint8_t*)"OK");                //测试AT
	send_at((uint8_t*)"AT+RST\r\n",(uint8_t*)"OK");                //重启
	//memset(uart2.rv_buffer, 0, strlen((const char*)uart2.rv_buffer));
	HAL_Delay(2000);
	//send_at((uint8_t*)"ATE0\r\n",(uint8_t*)"OK");              //关闭回显
	send_at((uint8_t*)"AT+BLEINIT=2\r\n",(uint8_t*)"OK");		//STA 模式(做为服务�??????)
	send_at((uint8_t*)"AT+BLEGATTSSRVCRE\r\n",(uint8_t*)"OK");		//创建服务
	send_at((uint8_t*)"AT+BLEGATTSSRVSTART\r\n",(uint8_t*)"OK");		//�??????启服�??????
	send_at((uint8_t*)"AT+BLEADDR?\r\n",(uint8_t*)"OK");		//获取其MAC地址
	send_at((uint8_t*)"AT+BLEADVPARAM=50,50,0,0,7,0,,\r\n",(uint8_t*)"OK");		//设置广播参数
	send_at((uint8_t*)"AT+BLEADVDATA=\"02010606094553503332030302A0\"\r\n",(uint8_t*)"OK");		//设置广播数据,名字"ESP32"
	send_at((uint8_t*)"AT+BLEADVSTART\r\n",(uint8_t*)"OK");		//�??????始广�??????
	HAL_Delay(7000);		//缓一�??????

	send_at((uint8_t*)"AT+BLEGATTSSRV?\r\n",(uint8_t*)"OK");		//查询服务
	send_at((uint8_t*)"AT+BLEGATTSCHAR?\r\n",(uint8_t*)"OK");		//发现特征
	send_at((uint8_t*)"AT+BLESPPCFG=1,1,7,1,5\r\n",(uint8_t*)"OK");		//配置 Bluetooth LE SPP
	send_at((uint8_t*)"AT+BLESPP\r\n",(uint8_t*)"OK");		//使能 Bluetooth LE SPP
}






/*
	* @name   send_at
	* @brief  发送AT指令
	* @param  AT_Command  -> 待发送的AT指令
	          Respond_Str -> 回应数据中包含的字符串
	* @retval None
*/
static void send_at(uint8_t * at_cmd, uint8_t * respond_str)
{
	uint8_t* const  p_at_cmd  = at_cmd;   //尽量不要对形参操作
	uint8_t* const  p_respond_str  = respond_str;

	printf("**************start!**************\r\n");

	//memset(uart2.recv_buffer, 0, uart2_recv_len);

	//发送AT指令
	uart2.send_string(p_at_cmd);

	//打印信息
	//printf("%s",p_at_cmd);



	while(strstr((const char*)uart2.recv_buffer,"\r\n") == NULL)
	{
		printf("send at cmd failed\r\n");
		break;
	}

	//延时10ms,接收完全部字节
	HAL_Delay(10);

	//模块回应数据处理处理
	if (strstr((const char*)uart2.recv_buffer, (const char*)p_respond_str))
	{
		printf("%s\r\n", uart2.recv_buffer);
	}
	else if (strstr((const char*)uart2.recv_buffer, "busy") == NULL)
	{
		printf("send at cmd busy\r\n");
	}
	else if (strstr((const char*)uart2.recv_buffer, (const char*)p_respond_str) )
	{
		printf("send at cmd failed\r\n");
	}

	printf("**************end!**************\r\n");
	printf("\r\n");

	HAL_Delay(2000);

}
